# coding=utf-8
from bs4 import BeautifulSoup  # 网页解析，获取数据
import re  # 正则表达式，文字匹配
import urllib.request
import urllib.error  # 指定url，获取网页数据
import xlwt #写入excel
import sqlite3



def main():
    baseurl = "https://movie.douban.com/top250?start="
    # 1.爬取网页
    datalist = getData(baseurl)
    # savepath = "豆瓣电影Top250.xls"
    databasepath = "movie.db"
    # 3.保存数据
    # saveData(datalist,savepath)
    saveData2DB(datalist,databasepath)
    # askURL("https://movie.douban.com/top250?start=")
# 爬取网页


#影片详情的规则
findLink = re.compile(r'<a href="(.*?)">')  #创建正则表达式对象，表示规则
#影片图片
findImgSrc = re.compile(r'<img.*src="(.*?)"',re.S)
#影片片名
findTitle = re.compile(r'<span class="title">(.*)</span>')
#影片评分
findScore = re.compile(r'<span class="rating_num" property="v:average">(.*)</span>')
#评分人数
findCommentnum = re.compile(r'<span>(\d*)人评价</span>')
#影片概况
findInq = re.compile(r'<span class="inq">(.*)</span>')
#影片的相关内容
findBD = re.compile(r'<p class="">(.*?)</p>',re.S)

def getData(baseurl):
    datalist = []
    for i in range(0,10):  #调用获取页面信息的函数 10次
        url = baseurl + str(i*25)
        html = askURL(url) #保存获取到的源码
        # 2.逐一解析数据
        soup = BeautifulSoup(html,"html.parser")
        for item in soup.find_all('div',class_="item"):
            # print(item)
            data = [] #保存一部电影的所有信息
            item = str(item)

            link = re.findall(findLink,item)[0] #通过正则表达式查找指定的字符串
            data.append(link)      #添加链接
            imgSrc = re.findall(findImgSrc,item)[0]
            data.append(imgSrc)   #添加图片
            titles = re.findall(findTitle,item)
            if (len(titles) == 2):
                ctitle = titles[0]    #添加中文名
                data.append(ctitle)
                otitle = titles[1].replace("/","")  #去掉斜杆  添加外文名
                data.append(otitle)
            else:
                data.append(titles[0])
                data.append("  ")    #留空
            
            score = re.findall(findScore,item)[0]
            data.append(score)     #添加打分
            comnum = re.findall(findCommentnum,item)[0]
            data.append(comnum)   #添加打分人数
            inq = re.findall(findInq,item)
            if len(inq) != 0:
                inq = inq[0].replace("。","")   #去掉句号
                data.append(inq)
            else:
                data.append(' ')    #留空
            bd = re.findall(findBD,item)[0]
            bd = re.sub('<br(\s+)?/>(\s+)?'," ",bd)  #去掉<br/>
            bd = re.sub('/'," ",bd)   #替换/
            data.append(bd.strip())   #去掉前后的空格

            datalist.append(data)     #把处理好的一部电影信息写入datalist  


    return datalist

# 得到指定一个URL的网页内容


def askURL(url):
    head = {
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36"
    }
    # 用户代理告诉豆瓣服务器我们是什么类型的机器。
    request = urllib.request.Request(url, headers=head)
    html = ""
    try:
        response = urllib.request.urlopen(request)
        html = response.read().decode("utf-8")
        # print(html)
    except urllib.error.URLError as e:
        if hasattr(e, "code"):
            print(e.code)
        if hasattr(e, "reason"):
            print(e.reason)
    return html

# 保存数据


def saveData(datalist,savepath):
    print("save...")
    book = xlwt.Workbook(encoding="utf-8",style_compression=0)   #创建workbook对象
    sheet = book.add_sheet("豆瓣电影Top250",cell_overwrite_ok=True)    #创建工作表
    col = ("电影详情链接","图片链接","影片中文名","影片外文名","评分","评价数","概况","相关信息")
    for i in range(0,8):
        sheet.write(0,i,col[i])   #写入列名
    for i in range(0,250):
        print("第%d条"%(i+1)) 
        data = datalist[i]
        for j in range(0,8):
            sheet.write(i+1,j,data[j])
    
    book.save(savepath)

def saveData2DB(datalist,databasepath):
    init_db(databasepath)
    conn = sqlite3.connect(databasepath)
    cur = conn.cursor()
    

    for data in datalist:
        for index in range(len(data)):
            if index == 4 or index == 5:
                continue
            data[index] = '"'+data[index]+'"'
        sql = '''
            insert into movie250(
            info_link,pic_link,cname,ename,score,rated,introduction,info)
            values(%s)'''%",".join(data)
        cur.execute(sql)
        conn.commit()
    cur.close()
    conn.close()




def init_db(databasepath):
    sql = '''
        create table movie250
        (
        id integer primary key autoincrement,
        info_link text,
        pic_link text,
        cname varchar,
        ename varchar,
        score numeric,
        rated numeric,
        introduction text,
        info text
        )
    '''  #创建数据表
    conn = sqlite3.connect(databasepath)
    cursor = conn.cursor()
    cursor.execute(sql)
    conn.commit()
    conn.close()

if __name__ == "__main__":  # 当程序执行时
    # 调用函数
    main()
    print("爬取完毕...")
